package sk.fiit.vppj.eventmanager.image;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;

import sk.fiit.vppj.eventmanager.core.DatabaseManager;
import sk.fiit.vppj.eventmanager.core.Utils;

/**
 * Class helps to resize or store image files from input.
 * 
 * @author Marek
 * 
 */
public class ImageProcessor {
	private BufferedImage image = null;
	private final static Logger log = Logger.getLogger( ImageProcessor.class.getName() );

	public ImageProcessor(File file) {

		try {
			String extension = Utils.getExtension( file );
			if( extension != null ) {
				if( !extension.equals( "gif" ) && !extension.equals( "jpeg" ) && !extension.equals( "jpg" ) && !extension.equals( "png" ) ) {
					throw new IllegalArgumentException( "Imported photo is not in supported file format" );
				}
			}
			this.image = ImageIO.read( file );
		}
		catch ( IOException e ) {
			log.log( Level.SEVERE, "Can't read image!", e );
			e.printStackTrace();
		}

	}

	public BufferedImage resizeImage(int width, int height) {
		BufferedImage resizedImage = new BufferedImage( width, height, this.image.getType() );
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage( this.image, 0, 0, width, height, null );
		g.dispose();
		return resizedImage;
	}

	public BufferedImage resizeImageToWidth(int width) {
		int ratio = this.image.getWidth() / width;
		BufferedImage resizedImage = new BufferedImage( width, this.image.getHeight() / ratio, this.image.getType() );
		Graphics2D g = resizedImage.createGraphics();
		g.drawImage( this.image, 0, 0, width, this.image.getHeight() / ratio, null );
		g.dispose();

		return resizedImage;
	}

	/**
	 * Store image to file and updates reference in database
	 * @param file where image will be saved
	 * @param user_id id of user to which will be changed reference in photoPortrait column in database
	 */
	public void storePortraitImage(File file, int user_id) {
		try {
			ImageIO.write( resizeImageToWidth( 640 ), Utils.getExtension( file ), file );
			int types[] = { java.sql.Types.VARCHAR, java.sql.Types.INTEGER };
			DatabaseManager
					.getInstance()
					.getJdbcTemplate()
					.update( "UPDATE jos_event_manager_users SET photoPortrait = ? WHERE user_id = ?",
							new Object[] { file.getName(), user_id }, types );
		}
		catch ( IOException e ) {
			log.log( Level.WARNING, "Can't resize image file!", e );
			e.printStackTrace();
		}

	}
}
